import $copy from '@utils/copy'
import onInit from '../_utils/edit'
const { $fn, $http } = window

const Index = ({ table_name, folder, onEntity }) => ({
	modal: {
		title 		: 'Entity + Model',
		width 		: '100%',
		height 		: '100%',
		maxWidth 	: null,
		controls 	: {
			after: [
				{ label:'保存 Entity', click: () => {
					const entity = window.$formModalRef().formRef().getValue('entity')
					const model = window.$formModalRef().formRef().getValue('model')
					if( model.includes('impl Related') && model.includes('belongs_to') && model.includes('super::')) return $fn.msg.warning(`Model 数据模型有自定义，无法移动全部`)
					if( $fn.isEmpty(entity) ) return $fn.msg.warning(`Entity 数据模型【${table_name}】不能为空`)
					$http.post(null, 'file/save_model', { param: { folder, table_name, model: entity} }).then(()=>{
						$fn.msg.success(`Entity 数据模型【${table_name}】移动保存成功`)
						window.$formModalRef().close()
					})
				} },
				{ label:'替换 Model', ghost:1, click: () => {
					const entity = window.$formModalRef().formRef().getValue('entity')
					let model = window.$formModalRef().formRef().getValue('model')
					if( entity === model ) return $fn.msg.warning('Model 与 Entity 数据一致')
					if( model === ''  ){
						model = entity
					}else{
						let reg = /Model {([^}]+)}/g
						const entity_str = entity.match(reg)[0]
						const model_str = model.match(reg)[0]
						
						if( entity_str === model_str ) return $fn.msg.warning('Model 与 Entity 数据模型一致')
						
						model = model.replace(reg, entity_str)
					}
					
					window.$formModalRef().formRef().setValue({ model })
					$fn.msg.success(`Model 数据模型【${table_name}】替换成功`)
				} },
				{ label:'生成 Entity', click:() => {
					onEntity(()=>{
						$http.pull(null, 'file/read_model', { param:{ folder, table_name } }).then(data=>{
							window.$formModalRef().formRef().setValue({ entity: data?.entity ?? '' })
						})
					})
				} },
				{ label:'复制 Entity', ghost:1, click: () => $copy( window.$formModalRef().formRef().getValue('entity') ) },
				{ label:'复制 Model', ghost:1, click: () => $copy( window.$formModalRef().formRef().getValue('model') ) },
			],
			ok: { label:'保存 Model' }
		}
	},
	form: {
		labelWidth 	: 's3',
		className 	: 'pre-form',
		api 		: 'file/save_model',
		infoApi 	: 'file/read_model',
		param 		: { folder, table_name },
		backParam 	: { folder, table_name },
		setParam 	: () => ({ entity: null }),
		okTxt 		: `Model 数据模型【${table_name}】保存成功`,
		// close 		: false,
		data: [
			{ name:'entity', type:'textarea', maxLength: null, p:'Entity', r:1, _label:'Entity 数据模型', class:'jz-entity-textarea' },
			{ name:'model', type:'textarea', maxLength: null, p:'Model', r:1, _label:'Model 数据模型', class:'jz-model-textarea' },
		],
		onInit: () => {
			onInit('.jz-entity-textarea')
			onInit('.jz-model-textarea')
		}
	}
})
export default Index